<template>
	<view class="register-container">
		<view class="register-header">
			<text class="title">注册账号</text>
		</view>
		
		<view class="register-form">
			<u-form :model="formData" ref="uForm">
				<view class="form-item">
					<u-input v-model="formData.username" placeholder="请输入用户名" prefix-icon="account" 
						@blur="verifyUsername" />
				</view>
				
				<view class="form-item">
					<u-input v-model="formData.password" placeholder="请输入密码" prefix-icon="lock" 
						type="password" @change="removeLoginDisabled" />
				</view>
				
				<view class="form-item">
					<u-input v-model="formData.repassword" placeholder="请再次输入密码" prefix-icon="lock" 
						type="password" @blur="verifyRepassword" @change="removeLoginDisabled" />
				</view>
				
				<view class="form-item">
					<view class="captcha-container">
						<u-input v-model="formData.captcha" placeholder="请输入验证码" prefix-icon="checkmark-circle" 
							@blur="verifyCaptcha" />
						<canvas class="captcha-canvas" width="240rpx" height="90rpx" canvas-id="captchaCanvas" 
							@tap="refreshCaptcha"></canvas>
					</view>
				</view>
				
				<view class="form-item">
					<u-button type="primary" :disabled="isDisabled" @click="verifyLogin">立即注册</u-button>
				</view>
			</u-form>
			
			<view class="login-link">
				<u-button type="text" @click="goToLogin">已有账号？去登录</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					username: '',
					password: '',
					repassword: '',
					captcha: ''
				},
				show_num: [],
				isDisabled: true
			}
		},
		methods: {
			// 生成验证码
			generateCaptcha() {
				const ctx = uni.createCanvasContext('captchaCanvas', this)
				const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
				this.show_num = []
				
				// 清空画布
				ctx.clearRect(0, 0, 240, 90)
				
				// 绘制背景
				ctx.setFillStyle('#f5f5f5')
				ctx.fillRect(0, 0, 240, 90)
				
				// 绘制干扰线
				for(let i = 0; i < 3; i++) {
					ctx.setStrokeStyle(this.randomColor(150, 200))
					ctx.beginPath()
					ctx.moveTo(Math.random() * 240, Math.random() * 90)
					ctx.lineTo(Math.random() * 240, Math.random() * 90)
					ctx.stroke()
				}
				
				// 绘制验证码
				for(let i = 0; i < 4; i++) {
					const char = chars[Math.floor(Math.random() * chars.length)]
					this.show_num.push(char.toLowerCase())
					ctx.setFontSize(20)
					ctx.setFillStyle(this.randomColor(50, 150))
					ctx.rotate(Math.random() * 0.4 - 0.2)
					ctx.fillText(char, 20 + i * 20, 25)
					ctx.rotate(-(Math.random() * 0.4 - 0.2))
				}
				
				ctx.draw()
			},
			
			// 生成随机颜色
			randomColor(min, max) {
				const r = Math.floor(Math.random() * (max - min) + min)
				const g = Math.floor(Math.random() * (max - min) + min)
				const b = Math.floor(Math.random() * (max - min) + min)
				return `rgb(${r},${g},${b})`
			},
			
			// 刷新验证码
			refreshCaptcha() {
				this.generateCaptcha()
			},
			
			// 验证用户名
			async verifyUsername() {
				if (this.formData.username === "") {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				}
				
				try {
					const res = await uni.request({
						url: '/login/loginVerifyUsername/' + this.formData.username,
						method: 'GET'
					});
					
					if (res.data.code === 100) {
						uni.showToast({
							title: `用户${this.formData.username}已存在`,
							icon: 'none'
						})
						this.isDisabled = true;
						return false;
					} else {
						this.isDisabled = false;
						return true;
					}
				} catch (error) {
					console.error(error);
					return false;
				}
			},
			
			// 验证重复密码
			verifyRepassword() {
				if (this.formData.repassword === "") {
					uni.showToast({
						title: '请再次输入密码',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				} else if (this.formData.password === "") {
					uni.showToast({
						title: '请先输入密码',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				} else if (this.formData.repassword !== this.formData.password) {
					uni.showToast({
						title: '两次密码不相同',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				} else {
					this.isDisabled = false;
					return true;
				}
			},
			
			// 验证验证码
			verifyCaptcha() {
				const captcha_num = this.formData.captcha.toLowerCase();
				const real_num = this.show_num.join("");
				
				if (captcha_num === "") {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				} else if (captcha_num === real_num) {
					this.isDisabled = false;
					return true;
				} else {
					uni.showToast({
						title: '验证码错误',
						icon: 'none'
					})
					this.isDisabled = true;
					return false;
				}
			},
			
			// 移除禁用状态
			removeLoginDisabled() {
				this.isDisabled = false;
			},
			
			// 验证登录
			async verifyLogin() {
				if (!this.verifyUsername() || !this.verifyCaptcha() || !this.verifyRepassword()) {
					return;
				}
				
				try {
					const res = await uni.request({
						url: '/login/register',
						method: 'POST',
						data: {
							username: this.formData.username,
							password: this.formData.password
						}
					});
					
					if (res.data.code === 100) {
						uni.showToast({
							title: '注册成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateTo({
								url: res.data.extend.url
							});
						}, 1500)
					} else {
						uni.showToast({
							title: '注册失败',
							icon: 'none'
						})
						this.isDisabled = true;
					}
				} catch (error) {
					console.error(error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			},
			
			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		},
		onReady() {
			this.generateCaptcha()
		}
	}
</script>

<style lang="scss">
.register-container {
	padding: 40rpx;
	
	.register-header {
		text-align: center;
		margin-bottom: 60rpx;
		
		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.register-form {
		.form-item {
			margin-bottom: 30rpx;
		}
		
		.captcha-container {
			display: flex;
			align-items: center;
			position: relative;
			padding-right: 240rpx;
			
			.captcha-canvas {
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 240rpx !important;
				height: 90rpx !important;
				flex-shrink: 0;
			}
		}
		
		.login-link {
			text-align: center;
			margin-top: 30rpx;
		}
	}
}
</style>
